use super::LEN;
use heapless::Vec;
use nrf_softdevice::ble::{gatt_client, Connection};

#[nrf_softdevice::gatt_client(uuid = "6460")]
#[derive(Clone)]
pub struct Tx {
    #[characteristic(uuid = "6461", write)]
    rx: Vec<u8, LEN>,
}
impl Tx {
    pub async fn new(conn: &Connection) -> Option<Self> {
        gatt_client::discover::<Tx>(conn).await.ok()
    }
    pub async fn send(&self, data: &[u8]) -> Result<(), ()> {
        let mut remain: &[u8] = &data;
        while remain.len() > LEN {
            let (left, right) = remain.split_at(LEN);
            let err = self.rx_write(Vec::from_slice(left).unwrap()).await;
            if err.is_err() {
                return Err(());
            }
            remain = right;
        }
        if remain.len() != 0 {
            let err = self.rx_write(Vec::from_slice(remain).unwrap()).await;
            if err.is_err() {
                return Err(());
            }
        }
        Ok(())
    }
}
